/**
 * 健康检查路由处理模块
 * @author HalRui
 * @version 1.0.0
 * @description 提供系统健康检查、数据库连接状态监控和统计信息查询等功能
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const connectionPool = require('../../utils/connection-pool');
const redisAPI = require('../../libs/redis-api');
const mongoService = require('../../utils/mongo-service');

/**
 * @route GET /health
 * @description 系统健康检查接口
 * @returns {Object} 系统状态信息
 */
router.get('/', async (req, res) => {
    try {
        const connectionStatus = connectionPool.getConnectionStatus();
        const healthCheck = await connectionPool.healthCheck();
        
        res.json({
            status: 'healthy',
            timestamp: new Date().toISOString(),
            connections: connectionStatus,
            health: healthCheck,
            uptime: process.uptime()
        });
    } catch (error) {
        res.status(500).json({
            status: 'unhealthy',
            timestamp: new Date().toISOString(),
            error: error.message,
            uptime: process.uptime()
        });
    }
});

/**
 * @route GET /health/redis
 * @description Redis 连接状态检查
 * @returns {Object} Redis 状态信息
 */
router.get('/redis', async (req, res) => {
    try {
        const redisHealth = await redisAPI.healthCheck();
        res.json(redisHealth);
    } catch (error) {
        res.status(500).json({
            status: 'error',
            message: 'Redis 健康检查失败',
            error: error.message
        });
    }
});

/**
 * @route GET /health/mongodb
 * @description MongoDB 连接状态检查
 * @returns {Object} MongoDB 状态信息
 */
router.get('/mongodb', async (req, res) => {
    try {
        const connectionStatus = connectionPool.getConnectionStatus();
        const mongoHealth = await connectionPool.healthCheck();
        
        res.json({
            connection: connectionStatus.mongodb,
            health: {
                mongodb: mongoHealth.mongodb
            }
        });
    } catch (error) {
        res.status(500).json({
            status: 'error',
            message: 'MongoDB 健康检查失败',
            error: error.message
        });
    }
});

/**
 * @route GET /health/stats
 * @description 连接池统计信息
 * @returns {Object} 连接池统计信息
 */
router.get('/stats', async (req, res) => {
    try {
        const mongoServiceInstance = new mongoService();
        const poolStats = await mongoServiceInstance.getPoolStats();
        const connectionStatus = connectionPool.getConnectionStatus();
        
        res.json({
            timestamp: new Date().toISOString(),
            connectionPool: poolStats,
            connections: connectionStatus,
            uptime: process.uptime()
        });
    } catch (error) {
        res.status(500).json({
            status: 'error',
            message: '获取连接池统计信息失败',
            error: error.message
        });
    }
});

module.exports = router;